/*
 * DefaultTrayProvider.java
 * 
 * Copyright 2007, 2008 Tiberiumlabs
 *
 * This file is part of Tiberiumlabs Lailaps.
 *
 * Tiberiumlabs Lailaps is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Tiberiumlabs Lailaps is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.tiberiumlabs.lailaps.tray;

import java.awt.Dimension;
import java.awt.Image;
import java.awt.Point;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JWindow;
import javax.swing.SwingUtilities;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import org.tiberiumlabs.lailaps.Mediator;
import org.tiberiumlabs.lailaps.actions.ActionFactory;
import org.tiberiumlabs.lailaps.gui.GUIBuilder;
import org.tiberiumlabs.lailaps.gui.elements.ExceptionDialog;
import org.tiberiumlabs.lailaps.resources.ImageLoader;

/**
 *
 * @author <a href="mailto:paranoid.tiberiumlabs@gmail.com">Paranoid</a>
 */
public class DefaultTrayProvider implements TrayProvider, MouseListener, PopupMenuListener {
    
    private GUIBuilder guiBuilder = Mediator.getMediator().getGuiBuilder();
    private TrayIcon trayIcon = null;
    private JWindow popupMenuParent;

    @Override
    public void createTrayIcon() {
        try {
            if (SystemTray.isSupported()) {
                SystemTray systemTray = SystemTray.getSystemTray();
                // creating tray with image and tooltip, PopumMenu will be done later
                //trayIcon = new TrayIcon(getImage(), "Lailaps Download Manager", createPopupMenu());
                trayIcon = new TrayIcon(getImage());
                // default icon is 22x22, resize it to real size
                trayIcon.setImageAutoSize(true);
                trayIcon.addMouseListener(this);
                
                systemTray.add(trayIcon);
                
                popupMenuParent = new JWindow();
            }
        } catch (Exception ex) {
            new ExceptionDialog(ex);
        }
    }
    
    @Override
    public void closeTrayIcon() {
        /*
        if (popupMenuParent != null) {
            popupMenuParent.dispose();
        }
         */
        SystemTray.getSystemTray().remove(trayIcon);
    }
    
    private Image getImage() {
        return Toolkit.getDefaultToolkit().getImage(ImageLoader.class.getResource("images/tray.png"));
    }
    
    public boolean isTrayIconVisible() {
        return trayIcon != null;
    }
    
    private JPopupMenu popupMenu = null;
    private JPopupMenu getPopupMenu() {
        if (popupMenu == null) {
            ActionFactory actionFactory = Mediator.getMediator().getActionFactory();
            popupMenu = new JPopupMenu("Lailaps");
            popupMenu.addPopupMenuListener(this);
            
            popupMenu.add(actionFactory.createAddElementAction());
            popupMenu.addSeparator();
            popupMenu.add(actionFactory.createStartAllAction());
            popupMenu.add(actionFactory.createStopAllAction());
            popupMenu.add(actionFactory.createRemoveCompletedAction());
            popupMenu.addSeparator();
            popupMenu.add(new JCheckBoxMenuItem(actionFactory.createShowMainWindowAction()));
            popupMenu.add(new JCheckBoxMenuItem(actionFactory.createShowDropTargetAction()));
            popupMenu.add(actionFactory.createSettingsDialogAction());
            popupMenu.addSeparator();
            popupMenu.add(actionFactory.createExitAction());
        }
        return popupMenu;
    }
    
    private void closeMenuParent() {
        if (popupMenuParent != null) {
            popupMenuParent.dispose();
        }
    }

    private long prevClick = 0;
     public void mouseClicked(MouseEvent e) {
        if (!e.isPopupTrigger() && e.getButton() == MouseEvent.BUTTON1) {
            long when = System.currentTimeMillis();
            if (when - prevClick <= 800) {
                if (guiBuilder.isMainWindowVisible()) {
                    guiBuilder.getMainWindow().dispose();
                }
                else {
                    guiBuilder.getMainWindow().setVisible(true);
                }
                prevClick = 0;
            }
            else {
                prevClick = when;
            }
            return;
        }
        final JPopupMenu menu = getPopupMenu();
        Dimension d = menu.getPreferredSize();
        Dimension s = Toolkit.getDefaultToolkit().getScreenSize();
        final Point p = new Point(e.getXOnScreen(), e.getYOnScreen());
        p.x = p.x + d.width > s.width ? p.x - d.width : p.x;
        p.y = p.y + d.height > s.height ? p.y - d.height : p.y;
        SwingUtilities.convertPointFromScreen(p, popupMenuParent);
        popupMenuParent.setVisible(true);
        // may be next two lines need to be executed from EvendDispatcher:
        menu.show(popupMenuParent.getContentPane(), p.x, p.y);
        popupMenuParent.toFront();
        prevClick = 0;
        return;
    }

    public void mousePressed(MouseEvent e) {
    }

    public void mouseReleased(MouseEvent e) {
    }

    public void mouseEntered(MouseEvent e) {
        trayIcon.setToolTip("Lailaps");
    }

    public void mouseExited(MouseEvent e) {
        trayIcon.setToolTip(null);
    }

    public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
    }

    public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
        closeMenuParent();
    }

    public void popupMenuCanceled(PopupMenuEvent e) {
        closeMenuParent();
    }
    
}
